package com.fzhucc.modules.businessCard.service.impl;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.businessCard.domain.BusinessCard;
import com.fzhucc.modules.businessCard.domain.BusinessCardStatus;
import com.fzhucc.modules.businessCard.domain.dto.BusinessCardDto;
import com.fzhucc.modules.businessCard.domain.dto.BusinessCardStatusDto;
import com.fzhucc.modules.businessCard.domain.dto.BusinessCardStatusLoveDto;
import com.fzhucc.modules.businessCard.domain.dto.BusinessCardStatusQueryCriteria;
import com.fzhucc.modules.businessCard.repository.BusinessCardRepository;
import com.fzhucc.modules.businessCard.repository.BusinessCardStatusRepository;
import com.fzhucc.modules.businessCard.service.BusinessCardStatusService;
import com.fzhucc.modules.businessCard.service.mapstruct.BusinessCardStatusMapper;
import com.fzhucc.modules.system.service.UserService;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author yyg
 * @description 服务实现
 * @date 2022-10-24
 **/
@Service
@RequiredArgsConstructor
public class BusinessCardStatusServiceImpl implements BusinessCardStatusService {

    private final BusinessCardStatusRepository businessCardStatusRepository;
    private final BusinessCardStatusMapper businessCardStatusMapper;

    private final UserService userService;

    private final BusinessCardRepository businessCardRepository;

    @Override
    public Map<String, Object> queryAll(BusinessCardStatusQueryCriteria criteria, Pageable pageable) {
        Page<BusinessCardStatus> page = businessCardStatusRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<BusinessCardStatusDto> map = page.map(businessCardStatusMapper::toDto);
        List<BusinessCardStatusDto> list = map.getContent();
        for (int i = 0; i < list.size(); i++) {
            BusinessCardStatusDto businessCardStatusDto = list.get(i);
            businessCardStatusDto.getId();
            Optional<BusinessCardStatus> res = businessCardStatusRepository.findById(businessCardStatusDto.getId());
            if(res.isPresent()){
                BusinessCardStatus businessCardStatus = res.orElseGet(() -> new BusinessCardStatus());
                Integer businessCardId = businessCardStatus.getBusinessCardId();
                Optional<BusinessCard> businessCard = businessCardRepository.findById(businessCardId);
                if(businessCard.isPresent()){
                    BusinessCardDto businessCardDto = new BusinessCardDto();
                    businessCardDto.setId(businessCard.get().getId());
                    businessCardDto.setAffiliatedTradeUnion(businessCard.get().getAffiliatedTradeUnion());
                    businessCardDto.setUser(businessCard.get().getUser());
                    businessCardDto.setName(businessCard.get().getName());
                    businessCardDto.setAddress(businessCard.get().getAddress());
                    businessCardDto.setPhone(businessCard.get().getPhone());
                    businessCardDto.setPost(businessCard.get().getPost());
                    businessCardDto.setPhoto(businessCard.get().getPhoto());
                    businessCardStatusDto.setBusinessCardDto(businessCardDto);
                }
            }
        }
        return PageUtil.toPage(map);
    }

    @Override
    public List<BusinessCardStatusDto> queryAll(BusinessCardStatusQueryCriteria criteria) {
        return businessCardStatusMapper.toDto(businessCardStatusRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public BusinessCardStatusDto findById(Integer id) {
        BusinessCardStatus businessCardStatus = businessCardStatusRepository.findById(id).orElseGet(BusinessCardStatus::new);
        ValidationUtil.isNull(businessCardStatus.getId(), "BusinessCardStatus", "id", id);
        return businessCardStatusMapper.toDto(businessCardStatus);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BusinessCardStatusDto create(BusinessCardStatus resources) {
        //openid 和 businesscardid 都存在则不新增
        List<BusinessCardStatus> list = businessCardStatusRepository.findByUseridBusinessCardId(resources.getUserId(), resources.getBusinessCardId());
        if (list != null && list.size() > 0) {
            BusinessCardStatusDto businessCardStatusDto = new BusinessCardStatusDto();
            return businessCardStatusDto;
        } else {
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                throw new BadRequestException("用户ID未找到");
            }else{
                resources.setUserId(userId);
            }
            return businessCardStatusMapper.toDto(businessCardStatusRepository.save(resources));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> love(BusinessCardStatusLoveDto resources) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("用户ID未找到");
        }

        BusinessCard businessCard = businessCardRepository.findByUserid(userId);//名片
        if (businessCard!=null && businessCard.getId()== resources.getBusinessCardId()) {//自己收藏自己
            return new HashMap<String, String>(1) {{
                put("status", "unme");
            }};
        }

        List<BusinessCardStatus> list = businessCardStatusRepository.findByUseridBusinessCardId(userId, resources.getBusinessCardId());
        if (list != null && list.size() == 1) {
            BusinessCardStatus businessCardStatus = list.get(0);
            businessCardStatus.setBusinessCardId(resources.getBusinessCardId());
            businessCardStatus.setUserId(userId);
            businessCardStatus.setIsCollect(resources.getIsCollect());
            if (resources.getIsCollect() == 1) {
                businessCardStatusRepository.save(businessCardStatus);
                return new HashMap<String, String>(1) {{
                    put("status", "love");
                }};
            } else if (resources.getIsCollect() == 0) {
                businessCardStatusRepository.save(businessCardStatus);
                return new HashMap<String, String>(1) {{
                    put("status", "unlove");
                }};
            } else {
                return new HashMap<String, String>(1) {{
                    put("status", "fail");
                }};
            }

        } else {
            BusinessCardStatus businessCardStatus1 = new BusinessCardStatus();
            businessCardStatus1.setBusinessCardId(resources.getBusinessCardId());
            businessCardStatus1.setUserId(userId);
            businessCardStatus1.setIsCollect(resources.getIsCollect());

            if (resources.getIsCollect() == 1) {
                businessCardStatusRepository.save(businessCardStatus1);
                return new HashMap<String, String>(1) {{
                    put("status", "love");
                }};
            } else if (resources.getIsCollect() == 0) {
                businessCardStatusRepository.save(businessCardStatus1);
                return new HashMap<String, String>(1) {{
                    put("status", "unlove");
                }};
            } else {
                return new HashMap<String, String>(1) {{
                    put("status", "fail");
                }};
            }
        }
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            businessCardStatusRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<BusinessCardStatusDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (BusinessCardStatusDto businessCardStatus : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("用户", businessCardStatus.getUser());
            map.put("收藏的名片id", businessCardStatus.getBusinessCardDto().getId());
            map.put("是否收藏", businessCardStatus.getIsCollect());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}